package com.srwl.mytx.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;

import com.srwl.mytx.R;

import java.math.BigDecimal;

/**
 * 用于显示 主题详情页面中的标题栏里面的左右图标
 */
public class MyImageView extends androidx.appcompat.widget.AppCompatImageView {

    private static final String TAG = "MyImageView";
    private float position = 1;
    private int startColor;
    private int endColor;
    private Context context;
    private int id;
    private Bitmap bitmap;
    private Bitmap bitmapAlpha;
    private Paint paint;
    private Rect rect;
    private LinearGradient mLinearGradient;
    private Matrix mScaleMatrix;
    private boolean isFirst = true;

    public MyImageView(Context context) {
        super(context);
        this.context = context;
        setWillNotDraw(false);
    }

    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        setWillNotDraw(false);
        initView(attrs);
    }

    public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        setWillNotDraw(false);
        initView(attrs);
    }

    private void initView(AttributeSet attrs) {
        TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.MyImageView);//获取配置属性
        position = tArray.getFloat(R.styleable.MyImageView_color_position, 1f);
        startColor = tArray.getInt(R.styleable.MyImageView_start_color, getResources().getColor(R.color.white));
        endColor = tArray.getInt(R.styleable.MyImageView_end_color, getResources().getColor(R.color.text_gray));
        id = tArray.getResourceId(R.styleable.MyImageView_my_drawable, -1);
        tArray.recycle();
        bitmap = BitmapFactory.decodeResource(getResources(), id);
        bitmapAlpha = bitmap.extractAlpha();
        paint = new Paint();
        paint.setAntiAlias(true);//抗锯齿
        rect = new Rect();
        mScaleMatrix = new Matrix();
        setScaleType(ScaleType.MATRIX);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int measureWidth = 0;
        int measureHeight = 0;
        if (widthMode == MeasureSpec.EXACTLY) {//1073741824精确模式，对应是设置固定的宽高 layout_width="300dp"
            measureWidth = width;
        } else if (widthMode == MeasureSpec.AT_MOST) {// -2147483648最大模式，对应的在布局文件中设置：match_parent 或者是 wrap_content
            measureWidth = bitmap.getWidth() + getPaddingStart() + getPaddingEnd();
        }
        if (heightMode == MeasureSpec.EXACTLY) {
            measureHeight = height;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            measureHeight = bitmap.getHeight() + getPaddingTop() + getPaddingBottom();
        }
        setMeasuredDimension(measureWidth, measureHeight);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (isFirst) {
            isFirst = false;
            // 获取控件的宽度和高度
            int width = getWidth();
            int height = getHeight();
            int imageWidth = bitmap.getWidth();// 图片的宽度
            int imageHeight = bitmap.getHeight();// 图片的高度
            float scale = 1.0f;
            // 如果图片宽度大于控件宽度，但是图片高度小于控件 高度，我们要缩小图片
            if (imageWidth > width && imageHeight < height) {
                scale = width * 1.0f / imageWidth;
            }
            if (imageWidth < width && imageHeight > height) {  // 如果图片宽度小于控件宽度，但是图片高度大于控件 高度，我们要缩小图片
                scale = height * 1.0f / imageHeight;
            }
            if ((imageWidth > width && imageHeight > height) || (imageWidth < width && imageHeight < height)) { // 如果图片的宽度都 大于或小于控件宽度，我们则要对图片进行对应缩放，保证图片占满控件
                scale = Math.min(width * 1.0f / imageWidth, height * 1.0f / imageHeight);
            }

            // 图片缩放后，将图片要移动到控件中心
            int dx = width / 2 - imageWidth / 2;
            int dy = height / 2 - imageHeight / 2;
            mScaleMatrix.postTranslate(dx, dy);
            mScaleMatrix.postScale(scale, scale, width / 2, height / 2);

        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        genenateLinearGradient();
        paint.setShader(mLinearGradient);
        canvas.drawBitmap(bitmapAlpha, mScaleMatrix, paint);

        //以下是通过rect 确顶图片位置，这样没法对图片进行缩放，当图片尺寸大于布局中给定的固定尺寸时，图片会显示不完整
//            rect.set(0, 0, getWidth(), getHeight());
//            genenateLinearGradient();
//            paint.setShader(mLinearGradient);
//            canvas.drawBitmap(bitmapAlpha, rect, rect, paint);

    }

    private void genenateLinearGradient() {
        mLinearGradient = new LinearGradient(0, 0, 0, getMeasuredHeight(), new int[]{startColor, startColor, endColor, endColor}, new float[]{0f, position, position, 1}, Shader.TileMode.CLAMP);
    }


    private Bitmap changeColor(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int bitmapArray[] = new int[width * height];
        int count = 0;

        int redW = Color.red(startColor);
        int greenW = Color.green(startColor);
        int blueW = Color.blue(startColor);
        int redB = Color.red(endColor);
        int greenB = Color.green(endColor);
        int blueB = Color.blue(endColor);
        int red, green, blue;

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                float rate = new BigDecimal((float) y / height).setScale(2, BigDecimal.ROUND_FLOOR).floatValue();

                if (rate < position) {//如果该点的高度在 颜色分界线之上，那么该点颜色为startColor，反之，为endColor
                    red = redW;
                    green = greenW;
                    blue = blueW;
                } else {
                    red = redB;
                    green = greenB;
                    blue = blueB;
                }
                bitmapArray[count++] = Color.argb(Color.alpha(bitmap.getPixel(x, y)), red, green, blue);
            }
        }

        return Bitmap.createBitmap(bitmapArray, width, height, Bitmap.Config.ARGB_4444);
    }

    public void setColorPosition(float position) {
        if (this.position == position) {
            return;
        }
        this.position = position;


        requestLayout();
    }

    public void showStartColor() {
        if (position == 1) {
            return;
        }
        position = 1;
        requestLayout();
    }

    public void showEndColor() {
        if (position == 0) {
            return;
        }
        position = 0;
        requestLayout();
    }


}
